import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showToast } from 'vant'
import {
  createShare,
  getMyShareList,
  cancelShare,
  updateShare,
  getShare,
  verifySharePassword,
  recordShareDownload,
  type ShareInfo,
  type ShareListParams,
  type CreateShareParams,
  type ShareAccessResponse,
  type ShareVerifyResponse
} from '@/api/share'

export const useShareStore = defineStore('share', () => {
  const shareList = ref<ShareInfo[]>([])
  const loading = ref<boolean>(false)
  const pagination = ref({
    total: 0,
    page: 1,
    size: 20,
    pages: 0
  })
  const currentShare = ref<ShareAccessResponse | null>(null)

  const fetchMyShareList = async (params?: Partial<ShareListParams>) => {
    try {
      loading.value = true

      const requestParams: ShareListParams = {
        page: pagination.value.page,
        size: pagination.value.size,
        orderBy: 'createTime',
        orderType: 'desc',
        ...params
      }

      const response = await getMyShareList(requestParams)

      shareList.value = response.content
      pagination.value = {
        total: response.totalElements || response.total || 0,
        page: (response.number + 1) || response.page || 1, // 后端从0开始，前端从1开始
        size: response.size,
        pages: response.totalPages || response.pages || 0
      }

      return response
    } catch (error) {
      console.error('获取分享列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const createNewShare = async (params: CreateShareParams) => {
    try {
      const share = await createShare(params)
      showToast({
        type: 'success',
        message: '分享创建成功'
      })
      await fetchMyShareList()
      return share
    } catch (error) {
      console.error('创建分享失败:', error)
      throw error
    }
  }

  const removeShare = async (shareId: number) => {
    try {
      await cancelShare(shareId)
      showToast({
        type: 'success',
        message: '分享已取消'
      })
      await fetchMyShareList()
    } catch (error) {
      console.error('取消分享失败:', error)
      throw error
    }
  }

  const updateShareSettings = async (shareId: number, params: Partial<CreateShareParams>) => {
    try {
      const share = await updateShare(shareId, params)
      showToast({
        type: 'success',
        message: '分享设置已更新'
      })
      await fetchMyShareList()
      return share
    } catch (error) {
      console.error('更新分享设置失败:', error)
      throw error
    }
  }

  const accessShare = async (shareCode: string) => {
    try {
      const shareInfo = await getShare(shareCode)
      currentShare.value = shareInfo
      return shareInfo
    } catch (error) {
      console.error('访问分享失败:', error)
      throw error
    }
  }

  const verifyPassword = async (shareCode: string, password: string) => {
    try {
      const result = await verifySharePassword(shareCode, password)
      if (result.verified) {
        showToast({
          type: 'success',
          message: '密码验证成功'
        })
      }
      return result
    } catch (error) {
      console.error('密码验证失败:', error)
      throw error
    }
  }

  const downloadSharedFile = async (shareCode: string) => {
    try {
      await recordShareDownload(shareCode)
      showToast({
        type: 'success',
        message: '下载已开始'
      })
    } catch (error) {
      console.error('记录下载失败:', error)
      throw error
    }
  }

  const refreshShareList = () => {
    return fetchMyShareList()
  }

  const resetState = () => {
    shareList.value = []
    currentShare.value = null
    pagination.value = {
      total: 0,
      page: 1,
      size: 20,
      pages: 0
    }
  }

  const formatShareUrl = (shareCode: string): string => {
    return `${window.location.origin}/share/${shareCode}`
  }

  const getSharePermissionText = (permissions: number): string => {
    switch (permissions) {
      case 1:
        return '仅查看'
      case 2:
        return '可下载'
      default:
        return '未知权限'
    }
  }

  const formatExpireTime = (expireTime?: string): string => {
    if (!expireTime) return '永久有效'

    const expire = new Date(expireTime)
    const now = new Date()

    if (expire < now) return '已过期'

    return expire.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  return {
    shareList,
    loading,
    pagination,
    currentShare,

    fetchMyShareList,
    createNewShare,
    removeShare,
    updateShareSettings,
    accessShare,
    verifyPassword,
    downloadSharedFile,
    refreshShareList,
    resetState,
    formatShareUrl,
    getSharePermissionText,
    formatExpireTime
  }
})